package net;

import java.io.IOException;
import java.io.PrintWriter;

import message.Packet;
import message.handler.PersistentMessageHandler;
import message.handler.StatusHandler;

import comunity.Community;
import comunity.Status;

public class Sender implements Runnable {

	@Override
	public void run() {
		VirtualQueue vq = VirtualQueue.obtainVirtualQueue();
		Packet packet = null;
		while (true) {
			packet = vq.popMessage();
			try {
				this._run(packet);
			} catch (Throwable e) {
				this.handleConnectionError(packet);
				System.out.println("[Errore][Sender] "+packet.toXML());
			}
		}
	}

	private void handleConnectionError(Packet packet) {
		Community community = Community.obtainCommunity();
		String receiver = packet.getReceiver();

		community.setUserStatus(receiver, Status.OFFLINE);
		new Thread(new StatusHandler(receiver, Status.OFFLINE)).start();
		if (packet.isMessage()) {
			new Thread(new PersistentMessageHandler(packet, receiver)).start();
		}
	}

	private void _run(Packet packet) throws InterruptedException, IOException {
		Community c = Community.obtainCommunity();
		String receiver = packet.getReceiver();

		if(!c.existUserSocket(receiver) || c.isUserSocketClosed(receiver)){
			throw new IOException();
		}
		PrintWriter out = c.getUserPrintWriter(receiver);
		String packetRappresentation = packet.toXML();
		//Thread.sleep(1000);
		out.println(packetRappresentation);
		out.flush();
		
		System.out.println("[out] "+packetRappresentation);
	}

}